package com.briup.web.controller;

import com.briup.bean.ShopCar;
import com.briup.bean.User;
import com.briup.service.IShopCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class ShopCarController {
    @Autowired
    private IShopCarService shopCarService;

    @GetMapping(value = {"/toShopCar"})
    public String toShopCar(   HttpSession session, Model model){
        User u = (User) session.getAttribute("user");
        List<ShopCar> shopCarList = shopCarService.findUserAllShopCar(u.getId());
        model.addAttribute("shopCarList",shopCarList);
        return "shopCar";
    }

    @GetMapping(value = {"/addShopCar"})
    @ResponseBody
    public String addShopCar(HttpSession session,Long shopId){
        //这里需要判断一下这个商品在不在用户的购物车中，如过在的话就需要加一。
        // 不在的话生成新的购物车记录
        User u = (User) session.getAttribute("user");
        ShopCar shopCar = shopCarService.findByShopIdAndUserId(shopId,u.getId());
        if(shopCar!=null){
            //假如购物车中已经有了就数量加一
            shopCarService.updateShopCar(shopCar.getId(),shopCar.getNum()+1);
            return "success";
        }
        shopCarService.saveShopCar(1,u.getId(),shopId);
        return "success";
    }

    @GetMapping(value = {"/updateShopCar"})
    @ResponseBody
    public String updateShopCar(Long shopCarId,int num){
        shopCarService.updateShopCar(shopCarId,num);
        return "success";
    }
    @GetMapping(value = {"/delShopCar"})
    @ResponseBody
    public String delShopCar(Long shopCarId){
        shopCarService.deleteShopCar(shopCarId);
        return "success";
    }
}
